package com.grm.controller;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
import javax.servlet.http.HttpServletResponse;
 
import com.alibaba.fastjson.JSON;
 
import com.grm.pojo.ExportModel;
import com.grm.pojo.ImportModel;
import com.grm.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
 
/**
 * @author gaorimao
 * @date 2021/08/19
 */
@RestController
@Slf4j
@RequestMapping("/excel")
public class ExcelController {
    @PostMapping("/import")
    public List<ImportModel> read(@RequestParam("file")MultipartFile excel) throws IOException {
        List<ImportModel> datas = ExcelUtil.readExcel(excel.getInputStream(), excel.getOriginalFilename(),
            ImportModel.class);
        log.info("[excel] datas = {}", JSON.toJSONString(datas));
        return datas;
    }
 
    @GetMapping("/export")
    public String writeExcel(HttpServletResponse response) throws IOException {
        List<ExportModel> list = getList();
        String fileName = "Excel导出测试";
        String sheetName = "sheet1";
        ExcelUtil.writeExcel(response, list, fileName, sheetName, ExportModel.class);

        return "success";
    }
 
    /**
     * desc: 模拟数据
     *
     * @return {@link List<ExportModel>}
     */
    private List<ExportModel> getList() {
        List<ExportModel> modelList = new ArrayList<>();
        ExportModel firstModel = new ExportModel();
        firstModel.setName("李明");
        firstModel.setSex("男");
        firstModel.setAge(20);
        firstModel.setCreateTime(new Date());
        firstModel.setDoubleData(0.2683);
        firstModel.setStringTest("gaorimao");
        modelList.add(firstModel);
 
        ExportModel secondModel = new ExportModel();
        secondModel.setName("珍妮");
        secondModel.setSex("女");
        secondModel.setAge(19);
        secondModel.setCreateTime(new Date());
        secondModel.setDoubleData(0.2015);
        secondModel.setStringTest("tieren");
        modelList.add(secondModel);
 
        return modelList;
    }
}
